from rest_framework.views import APIView
from rest_framework.generics import ListAPIView
import re
from utils.response import APIResponse
from django.core.cache import cache
from . import serializers, throttles, models
from libs.tx_sms import sms


# 多方式登录
class LoginAPIView(APIView):
    authentication_classes = []
    permission_classes = []

    def post(self, request, *args, **kwargs):
        serializer = serializers.LoginModelSerializer(data=request.data)
        if serializer.is_valid():
            return APIResponse(
                data={
                    'id': serializer.user.id,
                    'username': serializer.user.username,
                    'token': serializer.token
                }
            )
        return APIResponse(1, 'failed', data=serializer.errors, http_status=400)


# 手机验证码登录
class LoginMobileAPIView(APIView):
    authentication_classes = []
    permission_classes = []

    def post(self, request, *args, **kwargs):
        serializer = serializers.LoginMobileSerializer(data=request.data)
        if serializer.is_valid():
            return APIResponse(
                data={
                    'username': serializer.user.username,
                    'token': serializer.token
                }
            )
        return APIResponse(1, 'failed', data=serializer.errors, http_status=400)


# 手机验证码注册
class RegisterMobileAPIView(APIView):
    authentication_classes = []
    permission_classes = []

    def post(self, request, *args, **kwargs):
        serializer = serializers.RegisterModelSerializer(data=request.data)
        if serializer.is_valid():
            obj = serializer.save()
            return APIResponse(0, '注册成功', data={
                "username": obj.username,
                "mobile": obj.mobile,
                "email": obj.email
            })
        return APIResponse(1, 'failed', data=serializer.errors, http_status=400)


# 发送短信验证码
class SMSAPIView(APIView):
    throttle_classes = [throttles.SMSRateThrottle]

    def post(self, request, *args, **kwargs):
        mobile = request.data.get('mobile')
        if not (mobile and re.match(r'^1[2-9][0-9]{9}$', mobile)):
            return APIResponse(2, '手机号有误')
        code = sms.get_code()
        # result = sms.send_msg(mobile, code, const.SMS_EXP // 10)
        result = sms.send_msg(mobile, code)
        print(result)
        if not result:
            return APIResponse(1, '发送验证码失败')
        # cache.set(f'sms_{mobile}{code}{const.SMS_EXP}')
        cache.set('sms_%s' % mobile, code, 2 * 60)
        print(f'>>>>>{code}' + '=' + cache.get(f"sms_{mobile}") + '<<<<<')
        return APIResponse(0, '发送验证码成功')


# 手机注册验证
class MobileAPIView(APIView):
    authentication_classes = []
    permission_classes = []

    def post(self, request, *args, **kwargs):
        mobile = request.data.get('mobile')

        # 不管前台处不处理格式校验，后台一定需要校验
        if not (mobile and re.match(r'^1[3-9][0-9]{9}$', mobile)):
            return APIResponse(2, '手机号格式有误')

        try:
            # 查到对象，已经注册
            models.User.objects.get(mobile=mobile)
            return APIResponse(1, '手机号已经注册')
        except:
            # 查不到对象，就会抛异常，即没有注册过
            return APIResponse(0, '手机未注册')


# 用户个人信息单查
from rest_framework.generics import RetrieveAPIView
class UserInfoRetrieveAPIView(RetrieveAPIView):
    queryset = models.User.objects.all()
    serializer_class = serializers.UserInfoModelSerializer


# 紧急联系人单增
class EmpersonAPIView(APIView):
    def post(self, request, *args, **kwargs):
        request_data = request.data
        if isinstance(request_data, dict):
            em_ser = serializers.EmPeopleModelSerializer(
                data=request_data
            )
            if em_ser.is_valid():
                em_obj = em_ser.save()
                return APIResponse(
                    results=serializers.EmPeopleModelSerializer(
                        em_obj
                    ).data
                )
            return APIResponse(
                1, msg=em_ser.errors
            )
        else:
            return APIResponse(
                1, 'data errors',
                http_status=400
            )

# 安全问题单增
class AddQuestionAPIView(APIView):
    def post(self, request, *args, **kwargs):
        request_data = request.data
        if isinstance(request_data, dict):
            em_ser = serializers.QuestionModelSerializer(
                data=request_data
            )
            if em_ser.is_valid():
                em_obj = em_ser.save()
                return APIResponse(
                    results=serializers.QuestionModelSerializer(
                        em_obj
                    ).data
                )
            return APIResponse(
                1, msg=em_ser.errors
            )
        else:
            return APIResponse(
                1, 'data errors',
                http_status=400
            )

# 安全问题群查
from .filters import QuestionFilterSet
# OrderingFilter排序， SearchFilter搜索
from rest_framework.filters import OrderingFilter,SearchFilter
from django_filters.rest_framework import DjangoFilterBackend
class QuestionListAPIView(ListAPIView):
    queryset = models.Question.objects.all()
    serializer_class = serializers.QuestionModelSerializer

    #配置过滤器
    filter_backends = [OrderingFilter, SearchFilter, DjangoFilterBackend]

    filter_class = QuestionFilterSet

# 投诉列表群查
from .filters import ComplainFilterSet
class CompliainInfoListAPIView(ListAPIView):
    queryset = models.Complain.objects.all()
    serializer_class = serializers.ComplainModelSerializer

    #配置过滤器
    filter_backends = [OrderingFilter, SearchFilter, DjangoFilterBackend]

    filter_class = ComplainFilterSet

# 修改密码单改
class ChangePwdAPIView(APIView):

    def put(self, request, *args, **kwargs):
        print(request.data)
        old_pwd = request.data['old_pwd']
        pwd = request.data['pwd']
        re_pwd = request.data['re_pwd']
        user_id = request.data['id']
        #获得请求用户
        user_obj = models.User.objects.filter(pk=user_id).first()
        if pwd != re_pwd:
            return APIResponse(1, '两次密码输入不一致')
        if not user_obj.check_password(old_pwd):
            return APIResponse(2, '密码输入有误')
        user_obj.set_password(pwd)
        user_obj.save()
        return APIResponse(0, '修改密码成功')


# 投诉订单单增
class OrderComplainAPIView(APIView):
    def post(self, request, *args, **kwargs):
        request_data = request.data
        if isinstance(request_data, dict):
            com_ser = serializers.ComplainModelSerializer(
                data=request_data
            )
            if com_ser.is_valid():
                em_obj = com_ser.save()
                return APIResponse(
                    results=serializers.ComplainModelSerializer(
                        em_obj
                    ).data
                )
            return APIResponse(
                1, msg=com_ser.errors
            )
        else:
            return APIResponse(
                1, 'data errors',
                http_status=400
            )

# 订单发票单增
class OrderReceiptAPIView(APIView):
    def post(self, request, *args, **kwargs):
        request_data = request.data
        if isinstance(request_data, dict):
            com_ser = serializers.ReceiptModelSerializer(
                data=request_data
            )
            if com_ser.is_valid():
                em_obj = com_ser.save()
                return APIResponse(
                    results=serializers.ReceiptModelSerializer(
                        em_obj
                    ).data
                )
            return APIResponse(
                1, msg=com_ser.errors
            )
        else:
            return APIResponse(
                1, 'data errors',
                http_status=400
            )


# 违章群查
from .filters import TrafficFilterSet
class TrafficListAPIView(ListAPIView):
    queryset = models.Traffic.objects.all()
    serializer_class = serializers.TrafficListModelSerializer

    # 配置过滤器
    filter_backends = [OrderingFilter, SearchFilter, DjangoFilterBackend]

    filter_class = TrafficFilterSet


# 发票群查
from .filters import ReceiptFilterSet
class ReceiptSearchListAPIView(ListAPIView):
    queryset = models.Receipt.objects.all()
    serializer_class = serializers.ReceiptListModelSerializer

    # 配置过滤器
    filter_backends = [OrderingFilter, SearchFilter, DjangoFilterBackend]

    filter_class = ReceiptFilterSet





